from django.shortcuts import render
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from django.urls import reverse
from django.forms.models import model_to_dict

from .forms import SpiderForm, TaskForm
from .models import Spider
from .models import Task

# Create your views here.
import requests
import time


def spider_detail(request, sid):
    spider = Spider.objects.get(id=sid)
    keys = Spider.get_sorted_keys()
    values = [getattr(spider, k) for k in keys]
    spider_id = spider.id
    
    tasks = spider.task_set.all().order_by("-task_id")
    return render(request, "spider/spider_detail.html", {"kv": zip(keys, values), "spider_id":spider_id, "tasks":tasks})


def task_list(request):
    page = request.GET.get("page", "1")
    size = request.GET.get("size", "20")
    try:
        page = int(page)
    except:
        page = 1
    try:
        size = int(size)
    except:
        size = 20
    start = (page - 1) * size
    end = start + size
    tasks = Task.objects.all()[start:end]
    page_count = Task.objects.count() // size + 1
    return render(request, "spider/task.html",
                  {"tasks":tasks,
                   "cur_page": page,
                   "size":size,
                   "pages":range(page_count)})


#"""
#---------------------------------task---------------------------------
#"""
#def add_task(request, sid):
#    if request.method == "POST":
#        form = TaskForm(request.POST)
#        if form.is_valid():
#            form.save(commit=True)
#        return HttpResponseRedirect(reverse("spider_detail", kwargs={"sid":sid}))
#
#    elif request.method == "GET":
#        spider = Spider.objects.get(id=sid)
#        task_id = int(round(time.time() * 1000))
#        empty_form = TaskForm(initial={"spider":spider, "task_id":task_id})
#        return render(request, "spider/task_add.html", {"form":empty_form})
#
#
#def update_task(request, tid):
#    task = Task.objects.get(task_id=tid)
#    if request.method == "POST":
#        form = TaskForm(request.POST)
#        if form.is_valid():
#            form_data = form.cleaned_data
#            for field in form_data.keys():
#                setattr(task, field, form_data[field])
#            task.save()
#            return JsonResponse({"status":"ok!"})
#    else:
#        empty_form = TaskForm(initial=model_to_dict(task))
#        return render(request, "spider/task_add.html", {"form":empty_form})
#
#
#def del_task(request):
#    try:
#        tid = int(request.GET["tid"])
#        sid = int(request.GET['sid'])
#    except:
#        return HttpResponseRedirect(reverse("spiders"))
#    else:
#        Task.objects.filter(task_id=tid).delete()
#        return HttpResponseRedirect(reverse("spider_detail", kwargs={"sid":sid}))


def test(request):
    spider = Spider.objects.get(id=5)
    keys = Spider.get_sorted_keys()
    values = [getattr(spider, k) for k in keys]
    spider_id = spider.id
    return render(request, "spider/test.html", {"kv": zip(keys, values), "spider_id":spider_id})


